package cn.donting.plugin.spring.boot.starter.plugin.autoconfiguration.resource;

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.NoSuchBeanDefinitionException;
import org.springframework.beans.factory.NoUniqueBeanDefinitionException;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @author donting
 * 2020-07-01 10:15
 */
public class PluginMainResource {

    private Map<String, PluginResource> pluginResourceMap;

    public PluginMainResource(Map<String, PluginResource> pluginResourceMap) {
        this.pluginResourceMap = pluginResourceMap;
    }

    public <T extends PluginResource> T getBean(String name, Class<? extends T> requiredType) throws BeansException{
        PluginResource pluginResource = pluginResourceMap.get(name);
        T cast = requiredType.cast(pluginResource);
        return cast;
    }



    public <T extends PluginResource> T getBean(Class<T> requiredType) throws BeansException{
        int count = 0;
        List<String> bean=new ArrayList<>();
        T t = null;
        for (Map.Entry<String, PluginResource> stringPluginResourceEntry : pluginResourceMap.entrySet()) {
            PluginResource value = stringPluginResourceEntry.getValue();
            if (value.getClass().equals(requiredType)) {
                count++;
                t=requiredType.cast(value);
                bean.add(stringPluginResourceEntry.getKey());
            }
        }
        if(count==0){
            throw new NoSuchBeanDefinitionException(requiredType);
        }
        if(count>1){
            throw new NoUniqueBeanDefinitionException(requiredType,count,bean.toString());
        }
        return t;
    }

    public PluginResource getBean(String name) {
        PluginResource pluginResource = pluginResourceMap.get(name);
        return pluginResource;
    }
}
